﻿using NovoSerDes.Funcs;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Packaging;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;

namespace NovoSerDes.Forms
{
    public partial class LogControl : UserControl
    {
        private ILogData _logData;
        public LogControl()
        {
            _logData = LogData.Instance;
            InitializeComponent();
            InsertTestData();
            dgvLogData.ContextMenuStrip = contextMenuStrip1;

        }
        public void InsertTestData()
        {
            AddRowNumberColumn();
            dgvLogData.DataSource = _logData.GetDataTableAllData;
            //dgvLogData.Columns[6];
            dgvLogData.Dock = DockStyle.Fill;
            dgvLogData.Columns["IsValid"].Visible = false;         
        }
        private void dgvLogData_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {            
            if (e.Value != null && e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                if (e.Value != null && e.Value != DBNull.Value) // 检查值不为空
                {
                    if (e.ColumnIndex == 1)
                    {
                        try
                        {
                            // 将值转换为十六进制字符串
                            int value = Convert.ToInt32(e.Value);
                            e.Value = string.Format("Ox{0}", value.ToString("X2"));
                            e.FormattingApplied = true;
                        }
                        catch (FormatException)
                        {
                            // 如果转换失败，则保持原始值
                            e.FormattingApplied = false;
                        }
                    }
                    else if(e.ColumnIndex == 3)
                    {
                        try
                        {
                            // 将值转换为十六进制字符串
                            int value = Convert.ToInt32(e.Value);
                            e.Value = string.Format("Ox{0}", value.ToString("X4"));
                            e.FormattingApplied = true;
                        }
                        catch(FormatException)
                        {
                            // 如果转换失败，则保持原始值
                            e.FormattingApplied = false;
                        }
                    }
                    else if (e.ColumnIndex == 4)
                    {
                        try
                        {
                            // 将值转换为十六进制字符串
                            int value = Convert.ToInt32(e.Value.ToString(),16);
                            e.Value = string.Format("Ox{0}", value.ToString("X8"));
                            e.FormattingApplied = true;
                        }
                        catch (FormatException)
                        {
                            // 如果转换失败，则保持原始值
                            e.FormattingApplied = false;
                        }
                    }
                    bool isValid = (bool)_logData.GetDataTableAllData.Rows[e.RowIndex]["IsValid"];
                    if (!isValid)
                    {
                        dgvLogData.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
                    }
                }                                                               

            }
        }

        private void dgvLogData_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            // 添加行号，行号从 1 开始
            dgvLogData.Rows[e.RowIndex].Cells["RowNumber"].Value = (e.RowIndex + 1).ToString();
            //if (dgvLogData.Rows[e.RowIndex].Cells[0].Value.ToString() != "")
            //{
            //    for (int ix = 0; ix < dgvLogData.Rows[e.RowIndex].Cells.Count; ix++)
            //    {
            //        dgvLogData.Rows[e.RowIndex].Cells[ix].Style.BackColor = Color.LightGray;
            //        dgvLogData.Rows[e.RowIndex].Cells[ix].Style.Font = new System.Drawing.Font("Calibri", 12F,
            //            System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            //    }
            //}
        }

        // 在适当的地方调用这个方法来添加新的行号列
        private void AddRowNumberColumn()
        {
            // 创建一个新的 DataGridViewTextBoxColumn
            DataGridViewTextBoxColumn rowNumberColumn = new DataGridViewTextBoxColumn();
            // 设置列的名称
            rowNumberColumn.Name = "RowNumber";
            // 设置列的标题
            rowNumberColumn.HeaderText = "行号";
            // 将新的列插入到指定的位置，这里假设你希望添加到第一列之前
            dgvLogData.Columns.Insert(0, rowNumberColumn);
        }

       

        private void deleteToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            if(this.dgvLogData.SelectedRows.Count > 0)
            {
                DataGridViewRow row = this.dgvLogData.SelectedRows[0];
                int rowIndex = row.Index;
                _logData.DeleteData(rowIndex);
            }
            
        }

        private void clearToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _logData.DeleteAllData();
        }

        public void Highlights(string chip,string type,string addr)
        {
            // 清除所有行的背景颜色
            // 清除所有行的背景颜色
            foreach (DataGridViewRow row in dgvLogData.Rows)
            {
                //if(row.Index % 2 == 0)
                //{
                //    row.DefaultCellStyle.BackColor = Color.FromArgb(255,255,255);
                //}
                //else
                //{
                //    row.DefaultCellStyle.BackColor = Color.FromArgb(235, 243, 255);
                //}
                row.DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 255);

            }
            if (chip == "" && type == "" && addr == "") return;
            int count = 0;
            foreach (DataGridViewRow row in dgvLogData.Rows)
            {
                string Chipaddr = row.Cells[1].FormattedValue.ToString();
                string Type = row.Cells[2].FormattedValue.ToString();
                string Addr = Convert.ToInt32(row.Cells[3].FormattedValue.ToString().Substring(2), 16).ToString("X");
                
                bool ret = Chipaddr.ToUpper()==(chip.ToUpper()) || Type.ToUpper()==(type.ToUpper()) || Addr.ToUpper() == (addr.ToUpper());
                if (ret)
                {
                    row.DefaultCellStyle.BackColor = Color.Yellow;
                    dgvLogData.CurrentCell = row.Cells[0];
                    count++;
                    
                }
                
            }
            UIMessageTip.Show(string.Format("查询到{0}个数据", count.ToString()),null,1000,true);
        }

        public void FilterData(string chip, string type)
        {
            string filterExpression = "";
            if (chip != "" && type != "")
            {
                // 将筛选条件组合起来
                string chipFilter = "ChipAddr = " + Convert.ToUInt32(chip, 16); // 填入你想要筛选的 ChipAddr 值
                string typeFilter = "Type = '" + type + "'"; // 填入你想要筛选的 Type 值
                filterExpression = chipFilter + " AND " + typeFilter;
            }
            else if(chip == "" && type != "")
            {
                string typeFilter = "Type = '" + type + "'"; // 填入你想要筛选的 Type 值
                filterExpression = typeFilter;
            }
            else if(type == "" && chip != "")
            {
                string chipFilter = "ChipAddr = " + Convert.ToUInt32(chip, 16); // 填入你想要筛选的 ChipAddr 值
                filterExpression = chipFilter;
            }
            else
            {
                dgvLogData.DataSource = _logData.GetDataTableAllData;
                dgvLogData.Columns["IsValid"].Visible = false;
                return;
            }
            

            // 使用 Select 方法筛选符合条件的行
            DataRow[] filteredRows = _logData.GetDataTableAllData.Select(filterExpression);

            // 创建一个新的 DataTable 来存储筛选后的结果
            DataTable filteredDataTable = _logData.GetDataTableAllData.Clone(); // 复制结构，不包括数据
            foreach (DataRow row in filteredRows)
            {
                filteredDataTable.ImportRow(row); // 导入符合条件的行
            }

            // 将筛选后的 DataTable 绑定到 DataGridView
            dgvLogData.DataSource = filteredDataTable;
            dgvLogData.Columns["IsValid"].Visible = false;
        }

        private void dgvLogData_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            dgvLogData.FirstDisplayedScrollingRowIndex = e.RowIndex;
        }

        public void ChangeRowDefaultCellStyle()
        {
             DataGridViewCellStyle cellStyle = new DataGridViewCellStyle();
            cellStyle.Font = new Font("宋体", 12);
            dgvLogData.RowsDefaultCellStyle = cellStyle;
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {

        }
    }
}
